﻿package com.cw.war.ui
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	/**
	 * 全局跑秒器。
	 * @author DanielLu
	 */
	public final class Time extends EventDispatcher
	{
		// 默认的跑秒间隔
		private static const DELAY : int = 1000;
		//
		private static var instance : Time;

		public static function getInstance () : Time
		{
			if (instance == null) instance = new Time ();
			return instance;
		}

		private var timer : Timer;

		public function Time ()
		{
			if (instance != null) throw new Error ( "这是一个杯具，您已经实例化过了" );
			//
			this.timer = new Timer ( DELAY );
			this.timer.addEventListener ( TimerEvent.TIMER , this.__onTimer );
			this.timer.start ();
		}

		private function __onTimer ( e : TimerEvent ) : void
		{
			this.dispatchEvent ( new Event ( "timer" ) );
		}

		public function addTimerListener ( listener : Function ) : void
		{
			this.addEventListener ( "timer" , listener );
		}

		public function removeTimerListener ( listener : Function ) : void
		{
			this.removeEventListener ( "timer" , listener );
		}

		public function fireTimer () : void
		{
			this.dispatchEvent ( new Event ( "timer" ) );
		}
	}
}
